/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package session.stateless;

import entity.ActivityAddressEntity;
import entity.ActivityEntity;
import entity.ActivityOrganiserEntity;
import entity.EventEntity;
import entity.EventTimeEntity;
import entity.Ticket;
import exception.ExistException;
import java.util.Date;
import java.util.List;

import javax.ejb.EJB;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import util.enumeration.ActivityType;
import util.enumeration.SingaporeArea;

/**
 *
 * @author KohLi
 */
@Stateless
@LocalBean
public class EventSessionBean {

    @PersistenceContext
    private EntityManager entityManager;
    //@EJB
    //private StakeholderSessionBean stakeholderSession;
    private List<EventEntity> eventList;
    @EJB
    private SystemMessagesBean systemMessages;
    private EventEntity event;

    public void saveEvent(EventEntity e, ActivityEntity activity, ActivityAddressEntity venue, ActivityType activityType, ActivityOrganiserEntity org, Ticket ticket, EventTimeEntity time)
            throws ExistException {
        System.out.println("at session " + venue.getStreetName());



        if (checkDate(time) && checkVenue(venue) && checkActivityType(activityType)) {
            Date d = new Date();
            e.setActivityType(activityType);

            e.setVenue(venue);
            e.setOrganiser(org);
            e.setTicket(ticket);
            e.setWhen(time);
            e.setCreator(org.getOrganisationName());
            e.setCreationDate(d);

            entityManager.persist(e);

            //ActivityOrganiser organiser = entityManager.find(ActivityOrganiser.class, e.getOrganiser().getId());
            //org.setActivity(e); 
            //entityManager.persist(org);

            Ticket tick = new Ticket(ticket);
            tick.setEvent(e);
            tick.setCreationDate(d);
            entityManager.persist(tick);

            time.setEvent(e);
            entityManager.persist(time);




            //ActivityOrganiser organiser = new ActivityOrganiser(org);
            //entityManager.persist(organiser);


            //ActivityAddress where = new ActivityAddress(venue);
            //entityManager.persist(where);


            //e.setActivityType(activityType);
            //e.setVenue(where);
            //e.setOrganiser(organiser);

            //e.setWhen(time);
            //e.setCreator(organiser.getOrganisationName());
/*
            e.setCreationDate(d);
            entityManager.persist(e);
            
            EventTimeEntity when = new EventTimeEntity(time);
            when.setEvent(e);
            entityManager.persist(when);
            
            //set ticket
            Ticket tick = new Ticket(ticket);
            tick.setCreationDate(d);
            tick.setEvent(e);
            entityManager.persist(tick);
            
            
            System.out.println("eventid" + when.getEvent().getId());
            
             */

        }



    }

    public void saveEditEvent(EventEntity e, Ticket t) throws ExistException {
        System.out.println("saving edited event....");
        if (checkEditDate(e.getWhen()) && checkActivityType(e.getActivityType())) {
            System.out.println("event name: " + e.getEventName());
            EventEntity event = entityManager.find(EventEntity.class, e.getId());
            ActivityOrganiserEntity organiser = entityManager.find(ActivityOrganiserEntity.class, e.getOrganiser().getId());
            organiser.setOrganisationDesc(e.getOrganiser().getOrganisationDesc());
            organiser.setOrganisationName(e.getOrganiser().getOrganisationName());
            entityManager.persist(organiser);

            ActivityAddressEntity where = entityManager.find(ActivityAddressEntity.class, e.getVenue().getId());
            where.setBlkNumber(e.getVenue().getBlkNumber());
            where.setBuildingName(e.getVenue().getBuildingName());
            where.setPostalCode(e.getVenue().getPostalCode());
            where.setStreetName(e.getVenue().getStreetName());
            where.setUnitNumber(e.getVenue().getUnitNumber());
            entityManager.persist(where);
            EventTimeEntity when = entityManager.find(EventTimeEntity.class, e.getWhen().getId());
            when.setStartDate(e.getWhen().getStartDate());
            when.setEndDate(e.getWhen().getEndDate());
            when.setOpeningHoursEnum(e.getWhen().getOpeningHoursEnum());
            when.setClosingHoursEnum(e.getWhen().getClosingHoursEnum());

            //event.setOrganiser(organiser);
            //event.setVenue(where);
            event.setActivityType(e.getActivityType());
            //event.setWhen(when);
            event.setEventName(e.getEventName());
            event.setEventDesc(e.getEventDesc());
            event.setEventUrl(e.getEventUrl());
            Date d = new Date();
            event.setLastEditDate(d);
            entityManager.persist(event);

            Ticket ticket = entityManager.find(Ticket.class, t.getId());
            System.out.println("ticket id\t" + t.getId());
            System.out.println("ticket pricing \t" + t.getPrice());
            ticket.setEvent(event);
            ticket.setLastEditDate(d);
            ticket.setTicketName(t.getTicketName());
            ticket.setPrice(t.getPrice());
            ticket.setTicketDesc(t.getTicketDesc());
            entityManager.merge(t);
        }
    }

    public void deleteEvent(EventEntity e, Ticket t) throws ExistException {
        System.out.println("deleting event....");
        System.out.println("event name: " + e.getEventName());

        EventTimeEntity when = entityManager.find(EventTimeEntity.class, e.getWhen().getId());
        entityManager.remove(when);
        System.out.println("removed when....");




        ActivityOrganiserEntity organiser = entityManager.find(ActivityOrganiserEntity.class, e.getOrganiser().getId());
        entityManager.remove(organiser);
        System.out.println("removed organiser....");
        ActivityAddressEntity where = entityManager.find(ActivityAddressEntity.class, e.getVenue().getId());
        entityManager.remove(where);
        System.out.println("removed venue....");
        Ticket ticket = entityManager.find(Ticket.class, t.getId());
        entityManager.remove(ticket);
        System.out.println("removed ticket....");

//         entityManager.refresh(event);

        EventEntity event = entityManager.find(EventEntity.class, e.getId());
        entityManager.remove(event);
        System.out.println("removed event....");

        // 



    }

    private boolean checkDate(EventTimeEntity eventTime) throws ExistException {
        boolean success = true;
        Date today = new Date();


        if (eventTime.getEndDate().before(today) || eventTime.getStartDate().before(today)) {
            success = false;
            throw new ExistException("DATE_NOT_BEFORE_TODAY'S_DATE");
        } else if (eventTime.getStartDate().after(eventTime.getEndDate())) {
            success = false;
            throw new ExistException("DATE_NOT_BEFORE_START_DATE ");
        }
        return success;

    }

    private boolean checkEditDate(EventTimeEntity eventTime) throws ExistException {
        boolean success = true;
        Date today = new Date();
        if (eventTime.getStartDate().after(eventTime.getEndDate())) {
            success = false;
            throw new ExistException("DATE_NOT_BEFORE_START_DATE ");
        }
        return success;
    }

    private boolean checkVenue(ActivityAddressEntity venue) throws ExistException {
        boolean success = true;
        if (venue.getStreetName().isEmpty()) {
            success = false;
            throw new ExistException("EMPTY_STREET_NAME");
        }
        return success;

    }

    private boolean checkActivityType(ActivityType activityType) throws ExistException {
        boolean success = true;
        if (activityType.equals(null) || activityType == null) {
            success = false;
            throw new ExistException("EMPTY_ACTIVITY_TYPE");
        }
        return success;
    }

    public List<EventEntity> getAllEvent() {
        Query query = getEntityManager().createQuery("SELECT e FROM Event e");
        return query.getResultList();
    }

    public List<EventEntity> getEventByStakeholderName(String userName) {
        Query q = getEntityManager().createQuery("SELECT e FROM Event e WHERE e.organiser.organisationName = :userName");
        q.setParameter("userName", userName.trim());
        return q.getResultList();
    }

    public EventEntity getEventById(Long eventId) {
        //EventEntity event = new EventEntity();
        System.out.println("eventId at getEventById" + eventId);

        Query q = getEntityManager().createQuery("SELECT e FROM Event e WHERE e.id = :eventId");
        q.setParameter("eventId", eventId);

        if (q.getResultList().isEmpty()) {
            // might have to move this elsewhere....
            // EXCEPTION
        } else {
            System.out.println("Stakeholder exist");
            event = (EventEntity) q.getSingleResult();
            Ticket ticket = getTicketByEventId(eventId);
            setEvent(new EventEntity(event.getEventName(), event.getEventDesc(), event.getEventUrl(), event.getOrganiser(), event.getVenue(),
                    event.getActivityType(), event.getWhen(), ticket));
        }

        return event;
    }

    public EventEntity getEventByEventId(Long eventId) {
        EventEntity event = entityManager.find(EventEntity.class, eventId);

        return event;
    }

    public Ticket getTicketByEventId(Long eventId) {
        System.out.println("eventId at getTicketByEventId" + eventId);
        Query q = getEntityManager().createQuery("SELECT t FROM Ticket t WHERE t.event.id = :eventId");
        q.setParameter("eventId", eventId);
        return (Ticket) q.getSingleResult();
    }

    /**
     * @return the entityManager
     */
    public EntityManager getEntityManager() {
        return entityManager;
    }

    /**
     * @param entityManager the entityManager to set
     */
    public void setEntityManager(EntityManager entityManager) {
        this.entityManager = entityManager;
    }

    /**
     * @return the eventList
     */
    public List<EventEntity> getEventList() {
        return eventList;
    }

    /**
     * @param eventList the eventList to set
     */
    public void setEventList(List<EventEntity> eventList) {
        this.eventList = eventList;
    }

    /**
     * @return the systemMessages
     */
    public SystemMessagesBean getSystemMessages() {
        return systemMessages;
    }

    /**
     * @param systemMessages the systemMessages to set
     */
    public void setSystemMessages(SystemMessagesBean systemMessages) {
        this.systemMessages = systemMessages;
    }

    /**
     * @return the event
     */
    public EventEntity getEvent() {
        return event;
    }

    /**
     * @param event the event to set
     */
    public void setEvent(EventEntity event) {
        this.event = event;
    }
}
